<?php

namespace app\admin\common\controller;

use app\admin\framework\api\Permission;
use app\common\model\Dept;
use app\common\model\Insure;
use app\common\model\Order;
use app\common\service\DeptService;
use app\common\service\OrderService;
use app\common\service\UserService;
use app\common\utils\Excel;
use app\common\utils\Image;
use app\common\validate\OrderValidate;
use taoser\exception\ValidateException;
use think\facade\Db;

use app\common\model\OrderTrip;

#[Permission('所有订单', 'Order', 0)]
class OrderController
{




    #[Permission('查询')]
    public function select()
    {
        $keyword = request()->get('keyword', '');
        $orderStatus = request()->get('orderStatus');
        $start_dept_id = request()->get('start_dept_id');
        $end_dept_id = request()->get('end_dept_id');
        $dept_id = request()->get('dept_id');
        $carStatus = request()->get('carStatus');
        $timeType = request()->get('timeType', 1);
        $field = 'ot.*,o.eta,o.car_shelf_num,o.contract,o.status as order_status,o.total_price,o.order_sn,o.shipper_name,o.shipper_mobile,o.accept_name,o.accept_mobile,o.car_brand,o.address,o.end_address,(select name from em_dept where em_dept.id=ot.dept_id) as deptName';
        
        $where[] = ['o.order_sn|o.accept_mobile|o.shipper_mobile|o.shipper_name|o.accept_name|o.address|o.end_address|o.car_shelf_num','like','%'.$keyword.'%'];

        $whereOr = [];
        
        $userInfo = UserService::get();
        $roles = UserService::getRoleIds($userInfo['id']);
        if(!in_array(1,$roles)){
            if ($userInfo['dept_id'] != 91) {
                $where[] = ['ot.dept_id', '=', $userInfo['dept_id']];
            }
        }

        // 数据权限
        $dataAuth = UserService::getRoleDataAuth($userInfo['id']);
        if (!empty($dataAuth)) {
            $whereOr = [
                ['ot.start_dept_id', 'in', $dataAuth],
                ['ot.dept_id', 'in', $dataAuth],
                ['ot.end_dept_id', 'in', $dataAuth]
            ];
        }
        
        $timeBetween = request()->get('timeBetween',[]);
        if(!empty($timeBetween)){
            $timeBetween[1] = $timeBetween[1] . " 23:59:59";
            if ($timeType == 1) {
                $where[] = ['o.create_time','between',$timeBetween];
            } else if ($timeType == 2) {
                $where[] = ['ot.update_time','between',$timeBetween];
            } else if ($timeType == 3) {
                $where[] = ['o.finish_time','between',$timeBetween];
            }
        }
        if(isset($orderStatus) && $orderStatus >= 0){
            if ($orderStatus == 4 || $orderStatus == 8) {
                $where[] = ['o.status', '=', $orderStatus];
            } else {
                $where[] = ['o.status', '<>', 4];
            }
        }
        if(isset($start_dept_id) && !empty($start_dept_id)){
            $where[] = ['ot.start_dept_id', '=', $start_dept_id];
        }
        if(isset($end_dept_id) && !empty($end_dept_id)){
            $where[] = ['ot.end_dept_id', '=', $end_dept_id];
        }
        if(isset($dept_id) && !empty($dept_id)){
            $where[] = ['ot.dept_id', '=', $dept_id];
        }
        if(isset($carStatus) && $carStatus >= 0){
            $where[] = ['ot.status', '=', $carStatus];
        }
//        ->with(['depts'])
        $list = OrderTrip::alias('ot')
            ->join('order o','o.id = ot.order_id','left')
            ->where(function ($query) use ($whereOr) {
                if(!empty($whereOr)){
                    $query->whereOr($whereOr);
                }
            })
            ->where($where)
            ->field($field)
            ->order('id desc,order_id desc')
            ->paginate()
            ->each(function($item){
                if (isset($item->order_status)) {
                    $item->order_status_text = Order::STATUS[$item->order_status];
                } else {
                    $item->order_status_text = '';
                }
                if (isset($item->status)) {
                    $item->order_trip_status_text = Order::ORDER_TRIP_STATUS[$item->status];
                } else {
                    $item->order_trip_status_text = '';
                }
                if (isset($item->contract) && !empty($item->contract)) {
                    if (strpos($item->contract, 'http://sc.dm.ccjwcm.com') !== false) {
                        $item->contract = str_replace('http://sc.dm.ccjwcm.com', 'http://admin.nmshicheng.com', $item->contract);
                    }
                }
            });
        return apiSuccess(data: ['list' => $list->items(), 'total' => $list->total()]);
    }

    #[Permission('物流追踪')]
    public function logistics()
    {
        $id = request()->get('id', 0);
        return apiSuccess(data: OrderService::getLogistics($id));
    }
    
    #[Permission('创建订单', 'Order', 0)]
    public function create()
    {
        if (request()->method() === 'GET') {
            return apiSuccess(data: [
                'depts' => Dept::where('parent_id', 2)->select(),
                'pay_type' => Order::PAY_TYPE,
                'insures' => Insure::select(),
                'shipper_type' => Order::SHIPPER_TYPE,
                'collection_car_type' => Order::COLLECTION_CAR_TYPE
            ]);
        }
        
        if (request()->method() === 'POST') {
            $data = request()->post();
            OrderService::create($data);
            return apiSuccess('创建成功');
        }
    }
    
    #[Permission('配板发车', 'Order', 5)]
    public function departure()
    {
        if (request()->method() === 'GET') {
            return apiSuccess(data: [
                'depts' => DeptService::exclude(),
                'cars' => OrderService::getOutList(),
            ]);
        }
        if (request()->method() === 'POST') {
            $data = request()->post();
            OrderService::createDeparture($data);
            return apiSuccess('创建成功');
        }
    }
    
    #[Permission('生成合同')]
    public function createContract()
    {
        $data = request()->post();
        $orderService = new OrderService();
        $path = $orderService->createContract($data);
        return apiSuccess(data: [
            'image' => getImageUrl($path)
        ]);
    }

    #[Permission('订单详情')]
    public function detail()
    {
        $id = request()->get('id', 0);
        return apiSuccess(data: [
            'data' => OrderService::getDetail($id)
        ]);
    }

    #[Permission('获取办事处')]
    public function getData()
    {
        $data = Dept::where('parent_id', '=', 2)->where('status', 1)->order('list_order asc,create_time desc')->select()->toArray();
        return apiSuccess('ok', $data);
    }

    #[Permission('excelAll')]
    public function excelAll()
    {
        $keyword = request()->get('keyword', '');
        $timeBetween = request()->get('timeBetween', []);
        $orderStatus = request()->get('orderStatus', '');
        $start_dept_id = request()->get('start_dept_id', '');
        $end_dept_id = request()->get('end_dept_id', '');
        $dept_id = request()->get('dept_id');
        $carStatus = request()->get('carStatus', '');
        $timeType = request()->get('timeType', 1);

        $list = OrderService::getLists('adminAll', [
            'keyword' => $keyword,
            'timeBetween' => $timeBetween,
            'orderStatus' => $orderStatus,
            'start_dept_id' => $start_dept_id,
            'end_dept_id' => $end_dept_id,
            'dept_id' => $dept_id,
            'carStatus' => $carStatus,
            'timeType' => $timeType,
        ],true);
        // $field = 'ot.*,o.total_price,o.order_sn,o.shipper_name,o.shipper_mobile,o.accept_name,o.accept_mobile,o.car_brand,o.address,o.nickname,o.end_address,o.car_shelf_num,o.pay_type,o.total_price3,o.car_worth,o.insure_price';
        // $where[] = ['order_sn|accept_mobile|shipper_mobile','like','%'.$keyword.'%'];
        // $userInfo = UserService::get();
        // $roles = UserService::getRoleIds($userInfo['id']);
        // if(!in_array(1,$roles)){
        //     $where[] = ['ot.dept_id', '=', $userInfo['dept_id']];
        // }
        // $timeBetween = request()->get('timeBetween',[]);
        // if(!empty($timeBetween)){
        //     $where[] = ['o.create_time','between',$timeBetween];
        // }
        // $list = OrderTrip::alias('ot')->join('order o','o.id = ot.order_id','left')->where($where)->field($field)->order('id desc,order_id desc')->select()->each(function($item){
        // });

        $arr = [];
        $order = new Order();
        foreach ($list->toArray() as $key => $value){
            $oneData = [];
            $oneData[] = substr($value['create_time'],0,10);
            $oneData[] = $value['order_sn'];
            $oneData[] = 1;
            //2024-04-03 增加一个 建单人信息
//            $deptInfo = Db::name('dept')->where('id',$value['dept_id'])->find();
            $oneData[] = $value['dept_name'].' - '.$value['nickname'];
//            if(strpos($value['address'],'省') && strpos($value['address'],'市')){
//                $oneData[] = explode('省',explode('市',$value['address'])[0])[1];
//            }else{
//                $oneData[] = $value['address'];
//            }
            $oneData[] = $value['address'];
//            if(strpos($value['end_address'],'省') && strpos($value['end_address'],'市')){
//                $oneData[] = explode('省',explode('市',$value['end_address'])[0])[1];
//            }else{
//                $oneData[] = $value['end_address'];
//            }
            $oneData[] = $value['end_address'];
            $oneData[] = $value['car_brand'];
            $oneData[] = $value['car_shelf_num'];
            // switch($value['pay_type']){
            //     case 1:
            //         $oneData[]=$value['total_price1'];
            //         $oneData[]=0;
            //         break;
            //     case 2:
            //         $oneData[]=0;
            //         $oneData[]=$value['total_price'];
            //         break;
            //     case 3:
            //         $oneData[]=0;
            //         $oneData[]=0;
            //         break;
            // }
            $oneData[]=$value['total_price2'];
            $oneData[]=$value['total_price1'];
//            $oneData[] = $value['total_price3'];
            $oneData[] = $value['ot_status_text'];
            $oneData[] = $value['shipper_name'];
            $oneData[] = $value['shipper_mobile'];
            $oneData[] = $value['accept_name'];
            $oneData[] = $value['accept_mobile'];
            $oneData[] = $value['car_worth']."万";
            $oneData[] = $value['insure_price'];
            //中转数据
            // $nexts = json_decode($value['nexts'],true);

            $allPrice = 0;
            //1.先配置始发站
            $oneData[] = $value['total_price'];  //始发站运费
            $field = "obi.*,ob.driver_name,ob.driver_mobile,ob.license,ob.company_name,ob.company_mobile,ob.company_nickname,(select name from em_dept where em_dept.id = obi.next_dept_id) as next_dept_name";
//            $stattionInfo = Db::name('order_board_item')
//                ->alias('obi')
//                ->join('order_board ob', 'ob.id = obi.board_id', 'LEFT')
//                ->where('obi.order_id', $value['id'])
//                ->where('obi.dept_id', $value['dept_id'])
//                ->field($field)->find();
            //始发站车辆信息
            // if(!empty($stattionInfo)){
            //     $oneData[] = $stattionInfo['driver_name'].$stattionInfo['driver_mobile'];
            // }else{
            //     $oneData[] = "";
            // }

            $driver_name = [];
            $driver_mobile = [];
            $license = [];

            $allPrice += bcadd($allPrice,floatval($value['total_price']),2);

            $nexts = Db::name('order_board_item')
                ->alias('obi')
                ->join('order_board ob', 'ob.id = obi.board_id', 'LEFT')
                ->where('obi.order_id', $value['id'])
                ->field($field)->limit(3)->select();

            $allcost = Db::name('order_board_item')->where('order_id', $value['id'])->sum('total_price');

            $zzf = 0;
            $lzf = 0;

            if ($value["trip_status"] == 4 && count($nexts) > 0) {
                $nums = count($nexts);
                $zzf = ($nums - 1) * 20;
                if ($value["has_end_dept"] == 1) {
                    $lzf = 20;
                }
                $oneData[] = $zzf;
                $oneData[] = $lzf;
            } else {
                $oneData[] = 0;
                $oneData[] = 0;
            }

            $all_zdf = bcadd(bcadd((string)$zzf, (string)$lzf, 2), $allcost, 2);

            //2.中转站信息
            foreach ($nexts as $k=>$v){
//                $depts_name = Db::name('dept')->where('id',$v['next_dept_id'])->value('name');
                $detail = "运费:".$v['freight_price']."|加油费:".$v['fuel_price']."|装卸费:".$v['handling_price']."|叉车费:".$v['forklift_price']."|其他费:".$v['other_price']."|中转费:".$v['transfer_price']."|落站费:".$v['landing_price']."[备注：".$v['remarks']."]";
                if(!empty($v['next_dept_name'])){
                    $oneData[] = $v['next_dept_name'];
                    $oneData[] = $detail;
                    $oneData[] = $v['total_price'];
                    // $oneData[] = $stattionInfo['driver_name'].$stattionInfo['driver_mobile'];
                    $driver_name[]      = $v['driver_name']?$v['driver_name']:$v['company_name'];
                    $driver_mobile[]    = $v['driver_mobile']?$v['driver_mobile']:$v['company_mobile'];
                    $license[]          = $v['license']?$v['license']:$v['company_nickname'];
                }else{
                    $oneData[] = '';
                    $oneData[] = $detail;
                    $oneData[] = $v['total_price'];
                }
                // $allPrice = bcadd($allPrice,floatval($v['total_price']),2);
            }

            if(count($nexts) < 3){
                for($i=0;$i<3-count($nexts);$i++){
                    $oneData[] = "";
                    $oneData[] = "";
                    $oneData[] = "";
                }
            }
            // $oneData[] = str_replace('类型','',$order->getShipperTypeTextAttr("1",$value));
            // $oneData[] = $value['commission']; //返款金额
            // $allcost = bcadd($allPrice,floatval($value['commission']),2);//总成本
            // $oneData[] = $value['commission_data']; //返款对象信息
            // $oneData[] = $value['additional_remark']; //额外费用明细
            // $oneData[] = $value['additional_cost']; //额外费用金额
            // $allcost = bcadd($allcost,$value['additional_cost'],2);//总成本
            $oneData[] = $allcost;//全程运费
//            $oneData[] = bcsub(floatval($value['total_price']),$allcost,2);//单台毛利
            // $oneData[] = bcsub(bcsub(floatval($value['total_price']),$all_zdf,2), $value['insure_price'], 2);//单台毛利
            $oneData[] = bcsub(floatval($value['total_price']),$all_zdf,2);//单台毛利
            $oneData[] = !empty($driver_name)?implode(',', $driver_name):'';
            $oneData[] = !empty($driver_mobile)?implode(',', $driver_mobile):'';
            $oneData[] = !empty($license)?implode(',', $license):'';
            $oneData[] = $value["eta"];
            $oneData[] = $value["remark"];
            // print_r($oneData);exit;
            $arr[] = $oneData;
        }
        // print_r($arr);exit;
        $filePath = Excel::import('', [
            "日期",
            "运单号",
            "台数",
            "创建订单人",
            "起运地",
            "到达地",
            "车型品牌",
            "车辆识别码",
            "到付",
            "现付",
            "订单状态", // +
            "发车人",
            "电话",
            "收车人",
            "电话",
            "车值",
            "保险费(元)",
            "运输费总额",
            "付中转费20元/次",
            "付落地费20元/次",
            // "始发运营商姓名电话",
            "中转地1",
            "中转地1-费用明细",
            "中转地1-总费用（元）",
            // "中转地1运营商姓名电话",
            "中转地2",
            "中转地2-费用明细",
            "中转地2-总费用（元）",
            // "中转地2运营商姓名电话",
            "中转地3",
            "中转地3-费用明细",
            "中转地3-总费用（元）",
            // "中转地3运营商姓名话",
            "全程司机运输总费用（元）", // +
            // "客户类型",
            // "返款金额",
            // "返款姓名电话",
            // "额外费用明细",
            // "额外费用明细金额",
            // "全程运输运费（元）",
            "单台毛利润",
            "司机姓名", // +
            "司机电话", // +
            "司机车牌号", // +
            "预计到达时间", // +
            "备注"
        ], $arr);
        return apiSuccess(data: ['url'=>getImageUrl($filePath)]);
    }
}